package com.example.shiro_demo.ctrl;

import com.example.shiro_demo.vo.BaseResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: wuzs
 * @Date: 2019/10/14 13:51
 */
@Controller
@RequestMapping("/user")
public class HomeIndexController {
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse login(@RequestParam("username") String username, @RequestParam("password") String password) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 执行认证登陆
        try {
            subject.login(token);
        } catch (AuthenticationException e){
            String message;
            if (e.getMessage().length() > 13){
                message = "用户名或者密码错误";
            }else {
                message = e.getMessage();
            }
            return new BaseResponse(403, message);
        }catch (Exception e){
            return new BaseResponse(500, "未知错误");
        }
        if (subject.isAuthenticated()) {
            return new BaseResponse("登录成功");
        } else {
            token.clear();
            return new BaseResponse("登录失败");
        }
    }
    @RequestMapping("/unauthorized")
    @ResponseBody
    public BaseResponse unauthorized(){
        return new BaseResponse(401, "你没有该操作权限");
    }
    @RequestMapping("/unlogin")
    @ResponseBody
    public BaseResponse unlogin(){
        return new BaseResponse(403, "你尚未登陆，请登录");
    }
}
